<template>
  <div class="page-content">
    <h3>优惠券列表</h3>
    <el-row>
      <!-- <el-col :xs="24" :sm="12" :lg="6">
          <el-input placeholder="部门名称"></el-input>
        </el-col> -->
      <!-- <div style="width: 12px"></div> -->
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <!-- <el-button v-ripple>刷新</el-button> -->
        <el-button @click="showDialog('add')" v-ripple>新增优惠券</el-button>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="3">
        <el-form :model="searchForm">
          <el-form-item prop="queryCondition">
            <el-input placeholder="请输入优惠券名称" v-model="searchForm.queryCondition" @blur="getData"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <!--        <el-table-column label="ID" prop="id" width="50" align="center" />-->
        <el-table-column label="排序" prop="sort" align="center" width="80" />
        <el-table-column label="优惠券名称" prop="name" align="center" />
        <el-table-column label="优惠券类型" prop="type" #default="scope" align="center">
          <el-tag :type="getCouponType(scope.row.type)">
            {{ couponTagText(scope.row.type) }}
          </el-tag>
        </el-table-column>
        <el-table-column label="最低消费金额(元)" prop="minConsumption" align="center" />
        <el-table-column label="优惠方式" align="center" #default="scope">
          {{ scope.row.type === 1 ? `满${scope.row.minConsumption}优惠${scope.row.discountAmount}元` :
            `满${scope.row.minConsumption}打${scope.row.discountRate}折` }}
        </el-table-column>
        <el-table-column label="到期规则" prop="expiryType" #default="scope" align="center">
          {{ scope.row.expiryType === 1 ? `领取后${scope.row.validityDays}天内有效` : scope.row.expiryType === 2 ?
            `${scope.row.startTime}~${scope.row.endTime}内有效` : '' }}
        </el-table-column>
        <el-table-column label="已领取/总数量" align="center">
          <template #default="scope">
            {{ scope.row.getCount }}/ {{ scope.row.totalQuantity === -1 ? '无限制' : scope.row.totalQuantity }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" #default="scope" align="center">
          <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1"
            @change="EditStatus(scope.row.id, scope.row.status)" />
        </el-table-column>
        <el-table-column label="添加时间" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增优惠券' : '编辑优惠券'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
          <!-- <div>数字越小越靠前</div> -->
        </el-form-item>
        <el-form-item label="优惠券名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型：" prop="type">
          <el-radio-group v-model="form.type" :disabled="form.id ? true : false">
            <el-radio value="1">满减券</el-radio>
            <el-radio value="2">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="减免金额：" prop="discountAmount" v-if="form.type === '1'">
          <el-input v-model="form.discountAmount">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="折扣率：" prop="discountRate" v-if="form.type === '2'">
          <el-input v-model.number="form.discountRate" type="number" :min="0" :max="9.9" :step="0.1"
            placeholder="折扣率范围0-9.9，8代表打8折，0代表不折扣">
            <template #append>折</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费金额：" prop="minConsumption">
          <el-input v-model="form.minConsumption">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="到期类型：" prop="expiryType">
          <el-radio-group v-model="form.expiryType">
            <el-radio value="1">领取后生效</el-radio>
            <el-radio value="2">固定时间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.expiryType === '1'">
          <el-input v-model="form.validityDays">
            <template #prepend>有效期</template>
            <template #append>天</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="form.expiryType === '2'" style="width: 400px;">
          <el-date-picker v-model="fixedTime" type="daterange" range-separator="~" start-placeholder="开始时间"
            end-placeholder="到期时间" @change="validTimeChange" />
        </el-form-item>
        <el-form-item label="券适用范围：">
          <el-radio-group v-model="form.scope">
            <el-radio value="1">全场通用</el-radio>
            <el-radio value="2">班型</el-radio>
            <el-radio value="3">会员卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放总数量：" prop="totalQuantity">
          <el-input v-model="form.totalQuantity">
            <template #append>张</template>
          </el-input>
          <div style="color: #999;">
            发放的优惠券总数量，-1为不限制
          </div>
        </el-form-item>
        <el-form-item label="优惠券描述：" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch v-model="form.status" :inactive-value="0" :active-value="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { couponsList, addCoupons, delCoupons, editCoupons } from '@/api/marketing'

const dialogVisible = ref(false)
const fixedTime = ref<[Date, Date] | []>([])
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [{ required: true, message: '请输入等级描述', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  expiryType: [{ required: true, message: '请选择到期类型', trigger: 'change' }],
  discountAmount: [{ required: true, message: '请输入减免金额', trigger: 'blur' }],
  discountRate: [{ required: true, message: '请输入折扣率', trigger: 'blur' },
  {
    validator: (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入折扣率'))
      } else if (isNaN(value) || value < 0 || value > 9.9) {
        callback(new Error('折扣率范围为0-9.9'))
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }],
  minConsumption: [{ required: true, message: '请输入最低消费', trigger: 'blur' }],
  totalQuantity: [{ required: true, message: '请输入发放总数量', trigger: 'blur' }],
})

const form = reactive({
  id: '',
  name: '',
  type: '1',
  description: '',
  discountAmount: '',
  totalQuantity: '-1',
  sort: '1',
  discountRate: '',
  minConsumption: '',
  validityDays: '',
  status: 1,
  expiryType: '1',
  scope: '1',
  startTime: '',
  endTime: ''
})
const searchForm = reactive({
  queryCondition: ''
})

const getCouponType = (status: number) => {
  return status === 1 ? 'primary' : 'success'
}

const couponTagText = (status: number) => {
  let text = ''
  if (status === 1) {
    text = '满减券'
  } else if (status === 2) {
    text = '折扣券'
  }
  return text
}

const tableData = ref([])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.type = String(row.type)
    form.description = row.description
    form.discountAmount = row.discountAmount
    form.totalQuantity = row.totalQuantity
    form.sort = row.sort
    form.discountRate = row.discountRate
    form.minConsumption = row.minConsumption
    form.validityDays = row.validityDays
    form.status = row.status
    form.expiryType = String(row.expiryType)
    form.scope = String(row.scope)
    form.startTime = row.startTime
    form.endTime = row.endTime
    if (form.expiryType === '2') {
      fixedTime.value = [new Date(form.startTime), new Date(form.endTime)]
    }
  } else {
    form.id = ''
    form.name = ''
    form.type = '1'
    form.description = ''
    form.discountAmount = ''
    form.totalQuantity = ''
    form.sort = '1'
    form.discountRate = ''
    form.minConsumption = ''
    form.validityDays = ''
    form.status = 1
    form.expiryType = '1'
    form.scope = '1'
    form.startTime = ''
    form.endTime = ''
    fixedTime.value = []
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}


const deleteRole = (id: string) => {
  ElMessageBox.confirm('确定删除该优惠券吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await delCoupons([id])
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }

  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      const params = filterEmptyValues(form)
      if (form.id) {
        const res = await editCoupons(params)
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        const res = await addCoupons(params)
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      }
    }
  })
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const getData = async () => {
  tableLoading.value = true
  try {
    const params = filterEmptyValues(searchForm)
    const res = await couponsList({
      pageSize: pageSize.value,
      pageNum: pageNum.value,
      ...params
    })
    if (res.code === '00000') {
      tableData.value = res.data.list
      pageTotal.value = res.data.total
    }
  } catch { } finally {
    tableLoading.value = false
  }

}
const validTimeChange = (e: any) => {
  form.startTime = formatDate(e[0])
  form.endTime = formatDate(e[1])
}

const EditStatus = async (id: string, status: number) => {
  try {
    const res = await editCoupons({
      id, status
    })
    if (res.code === '00000') {
      ElMessage.success('修改成功')
    }
  } catch (e) {
  } finally {
    await getData()
  }
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }

  h3 {
    font-weight: bold;
    margin-bottom: 20px;
  }
}

:deep(.el-row) {
  justify-content: space-between;
}
</style>